package com.cj.wtrails.utils;

import android.os.Handler;

import com.cj.wtrails.MyApplication;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 * <p>
 * Created by yi on 2020/6/28.
 */
public class UpdateUtils {

    private String url = "https://d9f43c992961ae0750505398dbb4823c.dd.cdntips.com/imtt.dd.qq.com/16891/apk/9C52689F0451CBFBDBBF535ADD40D3A7.apk?mkey=5e9fdcc9777b5f80&f=24c3&fsname=com.tencent.weishi_6.7.6.588_676.apk&csr=1bbd&cip=119.123.121.117&proto=https";
    private int fileLength;
    private File file;
    private Handler handler;

    public UpdateUtils(Handler handler) {
        this.handler = handler;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public File getFile() {
        return file;
    }
    

    public void download() throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("connection", "keep-alive");
        fileLength = conn.getContentLength();
        System.out.println("文件长度：" + fileLength);
        int theadCount = 3;
        int size = fileLength / theadCount;
        System.out.println("每个下载量：" + size);
        conn.disconnect();
        file = new File(MyApplication.context.getCacheDir().getPath() + "/智慧步道.apk");
        System.out.println(file.getPath());
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        MyTask task0 = new MyTask(0, 0, size - 1, file);
        MyTask task1 = new MyTask(1, size, (2 * size) - 1, file);
        MyTask task2 = new MyTask(2, 2 * size, fileLength, file);
        fixedThreadPool.execute(task0);
        fixedThreadPool.execute(task1);
        fixedThreadPool.execute(task2);
        fixedThreadPool.shutdown();

    }


    class MyTask implements Runnable {

        private final int taskNum;
        private final int startPos;
        private final int endPos;
        private final File file;

        public MyTask(int taskNum, int startPos, int endPos, File file) {
            this.taskNum = taskNum;
            this.startPos = startPos;
            this.endPos = endPos;
            this.file = file;
        }

        @Override
        public void run() {
            try {
                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("connection", "keep-alive");
                //设置下载区间
                conn.setRequestProperty("range", "bytes=" + startPos + "-" + endPos);

                conn.connect();
                int code = conn.getResponseCode();
                if (code == 206) {
                    InputStream in = conn.getInputStream();
                    int serverSize = conn.getContentLength();
                    System.out.println("服务器返回的长度:" + serverSize);
                    System.out.println("bytes=" + startPos + "-" + endPos);
                    System.out.println(Thread.currentThread().getName() + "---" + taskNum);

                    RandomAccessFile out = new RandomAccessFile(file, "rw");
                    out.seek(startPos);
                    byte[] b = new byte[1024];
                    int len = -1;
                    while ((len = in.read(b)) != -1) {
                        out.write(b, 0, len);
                    }
                    out.close();

                    if (file.length() == fileLength) {
                        setFile(file);
                        handler.sendEmptyMessage(901);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
